﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rose.Models;
using Rose.Helper;

namespace Rose.Helper
{
    

    public class NewTrendHelpModel
    {

        public  Database_RoseEntities db = new Database_RoseEntities();

        private  int GetType(string type)
        {
            switch (type)
            {
                case "article": return 0;
                case "share": return 1;
                case "album" :return 2;
                case "feeling": return 3;
                    ////这里将表情填满;可以很方便；
                default: return -1;
            }
        }
    
       


        #region  add

        public  bool AddArticleTrend(Article model)
        {
            try
            {
                Trend saveModel = new Trend()
                {
                    TrendId = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    TargetId = model.Id,
                    UserId = model.UserId,
                    Type = GetType("article")
                };

                db.AddToTrends(saveModel);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }

        public  bool AddAlbumTrend(Photo model,string selfId)
        {
            try
            {
                Trend saveModel = new Trend()
                {
                    TrendId = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    TargetId =model.PhotoId,
                    UserId = selfId,
                    Type = GetType("album")
                };
                db.AddToTrends(saveModel);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }

        public  bool AddFeelingTrend(Feeling model)
        {
            try
            {
                Trend saveModel = new Trend()
                {
                    TrendId = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    TargetId = model.Id,
                    UserId = model.UserId,
                    Type = GetType("feeling")
                };
                db.AddToTrends(saveModel);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }
        public bool AddShareTrend(Share model)
        {
            try
            {
                Trend saveModel = new Trend()
                {
                    TrendId = Guid.NewGuid(),
                    CreateTime = DateTime.Now,
                    UserId = model.UserId,
                    Type = GetType("share"),
                    TargetId = model.Id
                };
                db.AddToTrends(saveModel);
                db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region  删除过时数据
        public  void DeleteOutTimeTrend(TimeSpan timeSpan)
        {
            int count = 0;
            List<Trend> trendList = db.Trends.Where(c => DateTime.Now - c.CreateTime > timeSpan).ToList();
            foreach (var trend in trendList)
            {
                try
                {
                    db.Trends.DeleteObject(trend);
                    count++;
                    if (count >= 100)
                    {
                        db.SaveChanges();
                        count = 0;
                    }
                }
                catch
                {
                    continue;
                }
            }
            db.SaveChanges();
            //这一步可能需要锁住数据库
        }
        #endregion

        #region  获取用户的好友及关注者名单
        private List<string> GetFriendList(string selfId)
        {
            List<string> returnModel = new List<string>();
            List<FriendRelation> relations = db.FriendRelations.Where(c => c.UserId == selfId).ToList();
            foreach (var relation in relations)
            {
                returnModel.Add(relation.FriendId);
            }
            return returnModel;
        }


        private List<string> GetFocusList(string selfId)
        {
            List<string> returnModel = new List<string>();
            List<FocusRelation> relations = db.FocusRelations.Where(c => c.UserId == selfId).ToList();
            foreach (var relation in relations)
            {
                returnModel.Add(relation.FocusId);
            }
            return returnModel;
        }

        public List<string> GetFriendAndFocusList(string selfId)
        {
            List<string> returnModel = GetFocusList(selfId);
            returnModel.AddRange(GetFriendList(selfId));
            return returnModel;
        }
        
        #endregion

        #region 获取好友动态列表


        private  List<Trend> GetFriendTrendList(string selfId, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.OrderByDescending(c => c.CreateTime).ToList();
            List<string> list = GetFriendList(selfId);
            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();
        }
        //返回了朋友已经关注者的动态

        public  List<NewTrendModel> GetFriendsTrendList(string selfId, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFriendTrendList(selfId, pagesize));
        }

        private   List<Trend> GetFriendMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.Where(c => c.CreateTime < lastTime).OrderByDescending(c => c.CreateTime).ToList();
            List<string> list = GetFriendList(selfId);
            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();
           
        }

        public  List<NewTrendModel> GetFriendsMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFriendMoreTrendList(selfId,lastTime, pagesize));
        }

        #endregion


        #region 获取好友以及关注者动态列表

        private List<Trend> GetFriendAndFocusTrendList(string selfId, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.OrderByDescending(c => c.CreateTime).ToList();
            List<string> list = GetFriendAndFocusList(selfId);

            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();
        }
        //返回了朋友已经关注者的动态

        public List<NewTrendModel> GetFriendsAndFocusTrendList(string selfId, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFriendAndFocusTrendList(selfId, pagesize));
        }

        private List<Trend> GetFriendAndFocusMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.Where(c => c.CreateTime < lastTime).OrderByDescending(c => c.CreateTime).ToList();

            List<string> list = GetFriendAndFocusList(selfId);
            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();

        }

        public List<NewTrendModel> GetFriendsAndFocusMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFriendAndFocusMoreTrendList(selfId, lastTime, pagesize));
        }

        #endregion


        #region  获取关注者的动态

        private List<Trend> GetFocusTrendList(string selfId, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.OrderByDescending(c => c.CreateTime).ToList();
            List<string> list = GetFocusList(selfId);
            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();
        }
        //返回了朋友F的动态

        public List<NewTrendModel> GetFocusesTrendList(string selfId, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFocusTrendList(selfId, pagesize));
        }

        private List<Trend> GetFocusMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            List<Trend> trendList = new List<Trend>();
            List<Trend> returnModel = new List<Trend>();

            trendList = db.Trends.Where(c => c.CreateTime < lastTime).OrderByDescending(c => c.CreateTime).ToList();
            List<string> list = GetFocusList(selfId);
            if (list.Count() > 0)
            {
                foreach (var trend in trendList)
                {

                    if (list.Contains(trend.UserId))
                    {
                        returnModel.Add(trend);
                    }

                }
            }  //end of count
            return returnModel.Take(pagesize).ToList();

        }

        public List<NewTrendModel> GetFocusesMoreTrendList(string selfId, DateTime lastTime, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetFocusMoreTrendList(selfId, lastTime, pagesize));
        }

        #endregion

        #region 获取关注者的心情

        

        #endregion



        #region 获取TrendMode列表

        private  NewTrendModel ChangeTrendToTrendModel(Trend model)
        {
            UserInfo userInfo =new CheckHelpModel().CheckUserInfo(model.UserId);
            NewTrendModel returnModel = new NewTrendModel()
            {
                UserId = model.UserId,
                Name = userInfo.Name,
                Type = model.Type,
                CreateTime = model.CreateTime.ToString(),
                ImagePath = userInfo.ImagePath,
                Title = string.Empty,
                Content = string.Empty,
                PhotoPath = string.Empty,
                Link=string.Empty,
                CommentCount=0,
                Id=model.TargetId.ToString()

            };
            int type = returnModel.Type;

            if (type == GetType("article"))
            {
                Article data = db.Articles.Where(c => c.Id == model.TargetId).FirstOrDefault();
                if (data == null)
                    return returnModel;
              
                returnModel.Title = CheckDataHelpModel.FormatLongText(data.EncodeTitle, 20);
                returnModel.Content = CheckDataHelpModel.FormatLongText(data.DecodeContent, 30);
                returnModel.Link = "/FriendTrend/FriendArticle?articleId=" + data.Id;
                returnModel.CommentCount = data.CommentCount;
                returnModel.ShareCount = data.ShareCount;
            }
           

            else if (type == GetType("album"))
            {
                Photo data = db.Photos.Where(c =>c.PhotoId==model.TargetId).FirstOrDefault();
                if (data == null)
                    return returnModel;

                returnModel.PhotoPath = "/Image/GetImage?image=/Photos/" + model.UserId + "/" + data.AlbumId.ToString() + "/" + data.PhotoId.ToString() + "." + data.Extension+"&width=200&height=200";
                Album album = db.Albums.Where(c => c.Id == data.AlbumId).FirstOrDefault();
                if (album == null)
                    return returnModel;
                returnModel.Title = album.Title;
                returnModel.Link = "/FriendTrend/FriendAlbum?friendId=" + model.UserId + "&albumId=" + data.AlbumId.ToString();
                returnModel.ShareCount = album.Hit;
                returnModel.CommentCount = album.PhotoCount;

            }  
                //只是表示更新了相册，需要点击查看该相册;
                //sharecount ===hit
                //commentcount==photocount
            else if (type == GetType("feeling"))
            {
                Feeling data = db.Feelings.Where(c => c.Id == model.TargetId).FirstOrDefault();
                if (data == null)
                    return returnModel;
             
                returnModel.Title = data.Feel;
                returnModel.Content = HttpContext.Current.Server.HtmlEncode(data.Description);
                returnModel.Link = "/FriendTrend/FriendFeelingList?friendId=" + model.UserId + "&currentpage=1";
                returnModel.CommentCount = data.CommentCount;
            }
            else if (type == GetType("share"))
            {
                Share data = db.Shares.Where(c => c.Id == model.TargetId).FirstOrDefault();
                if (data == null)
                    return returnModel;
                returnModel.Link = data.TargetLink;
                string varstring= HttpContext.Current.Server.HtmlEncode(data.Description);
                returnModel.Content = varstring;
                returnModel.Title=CheckDataHelpModel.FormatLongText(varstring,20);
                
            }

            //不存在 sharecount 
            return returnModel;


        }

        private  List<NewTrendModel> ChangeTrendsToTrendModels(List<Trend> list)
        {
            List<NewTrendModel> returnModel = new List<NewTrendModel>();
            foreach (var item in list)
            {
                NewTrendModel addModel = ChangeTrendToTrendModel(item);
                if (!string.IsNullOrEmpty(addModel.Title))
                    returnModel.Add(addModel);
            }
            return returnModel;
        }

      


        #endregion

        #region  获取一个朋友的动态
        private  List<Trend> GetAFriendTrendList(string friendId, int currentpage, int pagesize)
        {
            return db.Trends.Where(c => c.UserId == friendId).OrderByDescending(c=>c.CreateTime).Skip((currentpage - 1) * pagesize).Take(pagesize).ToList();
        }


        public  List<NewTrendModel> GetAFriendTrendModelList(string friendId, int currentpage, int pagesize)
        {
            return ChangeTrendsToTrendModels(GetAFriendTrendList(friendId, currentpage, pagesize));
        }

        #endregion

        #region 关于好友的生日
        private  string GetHowLong(TimeSpan howlong)
        {
            switch (howlong.Days)
            {
                case 0: return "今天";
                case 1: return "明天";
                case 2: return "后天";
                default: return howlong.Days.ToString() + "天后";
            }
        }

        public    List<BirthModel> GetFriendsByBirth(string selfId,int span)
        {
            List<BirthModel> returnModel = new List<BirthModel>();
            DateTime today = DateTime.Now;
            int thisyear = today.Year;

            foreach (string item in GetFriendAndFocusList(selfId))
            {
                UserInfo friendInfo =new CheckHelpModel().CheckUserInfo(item);
                if(friendInfo.BirthDate==null)
                    continue;
                DateTime friendBirth=(DateTime)friendInfo.BirthDate;
                try
                {
                    DateTime birthDay = new DateTime(thisyear, friendBirth.Month, friendBirth.Day);
                    TimeSpan howlong=birthDay-today;
                    if (howlong < new TimeSpan(span, 0, 0, 0)&& howlong.Days>=0)
                    {
                        BirthModel model = new BirthModel()
                        {
                            UserId = friendInfo.Id,
                            Name = friendInfo.Name,
                            ImagePath = friendInfo.ImagePath,
                            WhenBirth=GetHowLong(howlong)
                        };
                        returnModel.Add(model);
                       
                    }
                }
                catch
                {
                    continue;
                }
                
               
                
            }
            return returnModel;
        }

        #endregion
    }
}

